<template>
  <div v-if="getShow" style="width: 100%">
    <div class="wechat-order">
      <WeChatCode @success="loginCrm" />
    </div>
    <el-form class="login-form" label-position="top" label-width="120px" size="large">
      <el-form-item>
        <XButton
          :title="t('login.btnMobile')"
          class="w-[100%]"
          @click="setLoginState(LoginStateEnum.MOBILE)"
        />
      </el-form-item>
      <el-form-item>
        <XButton
          :loading="loginLoading"
          :title="t('login.backLogin')"
          class="w-[100%]"
          @click="handleBackLogin()"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import WeChatCode from '@/views/wecom/user/components/wxLogin.vue'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
const { setLoginState, getLoginState, handleBackLogin } = useLoginState()
import { usePermissionStore } from '@/store/modules/permission'
import { weComLogin } from '@/api/wecom/user/index'
import * as authUtil from '@/utils/auth'
const { t } = useI18n()
const redirect = ref<string>('')
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.WECHAT_LOGIN)
/*二维码成功之后登录*/
const loginCrm = async (code) => {
  const res = await weComLogin(code)
  if (res) {
    sessionStorage.setItem('userWx', JSON.stringify(res))
    if (res.weUserId) {
      setLoginState(LoginStateEnum.WECHAT_CHOICE)
    } else {
      authUtil.setTenantId(res.tenantId)
      authUtil.setTenantSign(res.tenantSign)
      authUtil.setToken(res)
      if (!redirect.value) {
        redirect.value = '/'
      }
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  }
}
</script>

<style scoped>
.wechat-order {
  width: 100%;
  height: 480px;
  margin-bottom: 22px;
  background: #fff;
}
</style>
